//
//  BackGroundTaskView.m
//  CoreBlueTooth
//
//  Created by bodyconn on 15/2/2.
//  Copyright (c) 2015年 bodyconn. All rights reserved.
//

#import "BackGroundTaskView.h"

@implementation BackGroundTaskView

DEF_SINGLETON(BackGroundTaskView)
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */
- (instancetype)init {
    self = [super init];
    if (self) {
        _isBackGroundTask = YES;
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(BecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(Bebackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"BecomeActive" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"Bebackground" object:nil];
}

#pragma mark --- 应用切换到后台模式 ---
- (void)Bebackground:(NSNotification *)Info {
    _isBackTast = YES;
    UIApplication *app = [UIApplication sharedApplication];
    
    self.bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:self.bgTask];
        self.bgTask = UIBackgroundTaskInvalid;
    }];
    
    _backTaskModeTimer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(applyForMoreTime) userInfo:nil repeats:YES];
}

- (void)applyForMoreTime {
    // 后台进行重连接
    if (_isBackGroundTask) {
    }
    
    if ([UIApplication sharedApplication].backgroundTimeRemaining < 120) {
        [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
        self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
            self.bgTask = UIBackgroundTaskInvalid;
        }];
    }
    
    _Runcount      += 30;
    _RunTotalCount += 30;
    if (_Runcount > 60) {
        if (!KK_BLESend.isSend) {
            _Runcount = 0;
            [self GetRealStep];
        }
    }
    //     NSLog(@"后台运行总时间>>>%d 运行间隔>>>%d",_RunTotalCount,_Runcount);
}

// 定时发送心跳包给蓝牙 获取实时步数
- (void)GetRealStep {
    [KK_BLESend sendGetRealStepWithUpdate:^(id object, KKBLEAcceptType type) {
    }];
}

- (void)getDeviceInfo {
    [KK_BLESend sendGetDeviceBasicInfoWithUpdate:^(id object, KKBLEAcceptType type) {
    }];
}

#pragma mark --- 应用切换到前台模式 ---
- (void)BecomeActive:(NSNotification *)Info {
    if (_backTaskModeTimer) {
        [_backTaskModeTimer invalidate];
        _backTaskModeTimer = nil;
        _Runcount          = 0;
        _RunTotalCount     = 0;
    }
}

@end

